# @Time : 2024-11-09 13:56
# @Author : Fioman 
# @Phone : 13149920693
"""
LSD算法检测,比Hough和HougP效果更好
"""
import random
import time

from public_tool import image_helper
from public_tool.image_helper import *


def line_find_by_lsd(image):
    cv.destroyAllWindows()
    show_image("LineFindOriginalImage", image)

    # 对图像进行阈值分割,并且中缝那里要填充

    lsd = cv.createLineSegmentDetector(0)
    lines = lsd.detect(image)
    lineRes = []
    imageShow = cv.cvtColor(image, cv.COLOR_GRAY2BGR)
    for line in lines[0]:
        x1, y1 = line[0][:2]
        x2, y2 = line[0][2:4]
        p1 = int(x1), int(y1)
        p2 = int(x2), int(y2)
        lineK, lineB = get_line_k_and_b((x1, y1), (x2, y2))
        angle = get_angle_by_k(lineK)
        lineLength = get_two_point_distance((x1, y1), (x2, y2))
        if abs(angle) > 15 or lineLength < int(80 * 2.4):
            continue
        cv.line(imageShow, p1, p2, random.choice(colorList), 2)
    show_image("lineFinded", imageShow)


if __name__ == '__main__':
    rootPath = r"F:\raw_2025\4pin_newline"
    image_helper.sizeScale = 4
    image_helper.showState = True
    fileList = image_helper.create_dir_and_get_filenames(rootPath)
    for index, file in enumerate(fileList, start=1):
        print("*" * 10 + f"第 {index} 张图 ({file}) 开始识别" + "*" * 10)
        imagePath = os.path.join(image_helper.fileDir, file)
        imageSrc = cv.imread(imagePath, cv.IMREAD_GRAYSCALE)
        calcStart = time.time()
        boardResult = image_helper.check_totalboard_is_ok(imageSrc)
        if boardResult.state:
            print(f"物料检测通过: {boardResult.info}")
        else:
            print(f"物料检测未通过: {boardResult.info}")
        data = boardResult.data
        box, offset, boardRes, boardResNoAngle, totalboard = (data.box, data.offset, data.boardRes,
                                                              data.boardResNoAngle, data.totalboard)
        if boardResNoAngle is not None:
            cv.imwrite(os.path.join(image_helper.keepTotalBoardResDir, file), boardResNoAngle)
        subImags, subOffsetPix = image_helper.get_sub_images(totalboard)
        res = line_find_by_lsd(subImags[0])
